import socket
import threading


def create_udp_server(host, port):
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    udp_socket.bind((host, port))
    print("正在等待客户端消息……")
    # num = 0

    while True:
        data, addr = udp_socket.recvfrom(1024)  # 这里接收数据
        # num += 1
        # print(f"收到客户端{num}号消息")
        # 传递data到线程函数
        client_handler = threading.Thread(target=handle_udp_client, args=(udp_socket, data, addr))
        client_handler.start()


def handle_udp_client(udp_socket, data, addr):
    # 解码接收到的数据
    request = data.decode("utf-8")
    print(f"客户端:{addr} 说: {request}")

    msg = input(f"请输入回复客户端的内容：")
    udp_socket.sendto(msg.encode("utf-8"), addr)


#本次测试

if __name__ == '__main__':
    host = "127.0.0.1"
    port = 8000
    create_udp_server(host, port)